<template>
  <div>
    <div style="margin-bottom: 10px; font-size: 14px; font-weight: 250; margin-left: 10px">
      <el-icon><CollectionTag /></el-icon>
      管理员管理
    </div>
    <el-card>
      <div>
        <el-button type="primary" size="large" @click="addAdmin">创建管理员</el-button>
      </div>
      <el-table :data="data.tableData" stripe style="width: 100%">
        <el-table-column prop="id" label="管理员ID" />
        <el-table-column prop="username" label="管理员用户名" />
        <el-table-column prop="permissionCount" label="权限个数" />
        <el-table-column label="操作">
          <template #default="scope">
            <el-button @click="updateAdmin(scope.row)" type="primary" icon="Edit" circle />
            <el-button @click="handleDel(scope.row.id)" type="danger" icon="Delete" circle />
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <el-dialog v-model="data.dialogFormVisible" title="编辑" width="500">
      <el-form ref="formRef" :rules="data.rules" :model="data.form" label-width="70px" style="padding: 20px">
        <el-form-item label="用户名" prop="username">
          <el-input size="large" v-model="data.form.username" placeholder="请输入用户名"></el-input>
        </el-form-item>
        <el-form-item label="权限" prop="priGroup">
          <el-checkbox-group v-model="data.priGroup">
            <el-checkbox label="1" name="priGroup">系管理</el-checkbox>
            <el-checkbox label="2" name="priGroup">专业管理</el-checkbox>
            <el-checkbox label="4" name="priGroup">班级管理</el-checkbox>
            <el-checkbox label="8" name="priGroup">学生管理</el-checkbox>
            <el-checkbox label="16" name="priGroup">教师管理</el-checkbox>
            <el-checkbox label="32" name="priGroup">课程管理</el-checkbox>
            <el-checkbox label="64" name="priGroup">选课修改</el-checkbox>
            <el-checkbox label="128" name="priGroup">管理员管理</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input size="large" v-model="data.form.password" placeholder="请输入密码"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <div>
          <el-button @click="data.dialogFormVisible = false" size="large">取消</el-button>
          <el-button type="primary" @click="handleSave" size="large">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import {reactive, watch, ref} from "vue";
import request from "@/utils/request.js";
import {ElMessage, ElMessageBox} from "element-plus";

const formRef = ref()

const data = reactive({
  dialogFormVisible: false,
  form: {
    username: "",
    password: "",
    privilege: 0
  },
  priGroup: [],
  tableData: [],
  rules: {
    username: [
      {required: true, message: "请输入用户名!", trigger: "blur"}
    ],
    password: [
      {required: true, message: "请输入密码!", trigger: "blur"}
    ],
  }
})

// 监听priGroup，计算privilege累加值
watch(() => data.priGroup, (newVal) => {
  data.form.privilege = newVal.reduce((sum, val) => sum + parseInt(val), 0);
}, { immediate: true, deep: true });

// 计算权限个数
const calculatePermissionCount = (privilege) => {
  let count = 0;
  const permissions = [1, 2, 4, 8, 16, 32, 64, 128];
  permissions.forEach(perm => {
    if (privilege & perm) count++;
  });
  return count;
}

const load = () => {
  request.get("admin/selectAll").then(res => {
    data.tableData = res.data.map(admin => ({
      ...admin,
      permissionCount: calculatePermissionCount(admin.privilege)
    }))
  })
}

load()

const addAdmin = () => {
  data.dialogFormVisible = true;
  data.form = {
    username: "",
    password: "",
    privilege: 0
  };
  data.priGroup = [];
}

const handleAdd = () => {
  request.post("admin/add", data.form).then(res => {
    if (res.code === "200") {
      ElMessage.success("创建成功")
      load()
      data.dialogFormVisible = false
    } else {
      ElMessage.error(res.msg)
    }
  })
}

const updateAdmin = (row) => {
  data.form = JSON.parse(JSON.stringify(row))  // 深拷贝
  data.dialogFormVisible = true

  // 重置priGroup
  data.priGroup = []

  // 将权限值解析为多选框选项
  const permissions = [1, 2, 4, 8, 16, 32, 64, 128]
  permissions.forEach(perm => {
    // 使用位运算检查是否拥有该权限
    if (row.privilege & perm) {
      data.priGroup.push(perm.toString())
    }
  })
  }

const handleEdit = () => {
  request.put("admin/update", data.form).then(res => {
    if (res.code === "200") {
      ElMessage.success("编辑成功")
      load()
      data.dialogFormVisible = false
    } else {
      ElMessage.error(res.msg)
    }
  })
}

const handleSave = () => {
  formRef.value.validate((valid) => {
    if(valid) {
      data.form.id ? handleEdit() : handleAdd()
    }
  })
}

const handleDel = (id) => {
  ElMessageBox.confirm(
      '删除后无法复原，是否确定删除',
      '删除提示',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      }
  ).then(() => {
    request.delete("admin/deleteById/" + id).then(res => {
      if(res.code === "200") {
        ElMessage.success("删除成功")
        load()
      } else {
        ElMessage.error(res.msg)
      }
    })
  }).catch(() => {
    ElMessage({
      type: 'info',
      message: '取消删除',
    })
  })
}
</script>